package com.jarchie.seemovies.mvp.presenter;

import com.jarchie.seemovies.mvp.Api;
import com.jarchie.seemovies.mvp.contact.MovieDetailContact;
import com.jarchie.seemovies.mvp.model.MovieDetailBean;
import com.seemovies.sdk.mvp.impl.BasePresenterImpl;
import com.seemovies.sdk.retrofit.ExceptionHelper;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Jarchie on 2017\11\9.
 * 描述：电影详情处理类
 */

public class MovieDetailPresenter extends BasePresenterImpl<MovieDetailContact.view> implements MovieDetailContact.presenter {

    public MovieDetailPresenter(MovieDetailContact.view view) {
        super(view);
    }

    @Override
    public void getData(int id) {
        Api.getInstance().movieDetailList(id)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        addDisposable(disposable);
                        view.showLoading();
                    }
                })
                .map(new Function<MovieDetailBean, MovieDetailBean.DataBean>() {
                    @Override
                    public MovieDetailBean.DataBean apply(@NonNull MovieDetailBean movieDetailBean) throws Exception {
                        return movieDetailBean.getData();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MovieDetailBean.DataBean>() {
                    @Override
                    public void accept(@NonNull MovieDetailBean.DataBean dataBean) throws Exception {
                        view.dismissLoading();
                        view.setData(dataBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        view.dismissLoading();
                        ExceptionHelper.handleException(throwable);
                    }
                });
    }

}
